#!/usr/bin/env bash
# ══════════════════════════════════════════════════════════════════════════════
# FurryOS: Sovereign Mansion Launcher (v2.1_v4)
# ══════════════════════════════════════════════════════════════════════════════
set -e

PROJECT_ROOT="$(cd "$(dirname "$0")" && pwd)"
GENERATED="$PROJECT_ROOT/../_generated"
ISO_ROOT="$GENERATED/iso-root"
SQUASHFS_ROOT="$GENERATED/work/squashfs-root"

# 1. Validation
if [ ! -d "$SQUASHFS_ROOT" ]; then
    echo "❌ Error: Den not found! Run ./build_furryos.sh first."
    exit 1
fi

echo "🦊 Opening the portal to the Sovereign Mansion..."

# 2. Find the MBR (Essential to fix the 'Checksum Error')
# This looks for the system's boot record template
MBR_BIN=$(find /usr/lib -name isohdpfx.bin 2>/dev/null | head -n 1 || echo "")

# 3. Rapid Sync (LZ4 is instant)
TEST_ISO="$GENERATED/mansion_portal.iso"
sudo rm -f "$ISO_ROOT/live/filesystem.squashfs"
echo "📦 Unpacking changes into the virtual medium..."
sudo mksquashfs "$SQUASHFS_ROOT" "$ISO_ROOT/live/filesystem.squashfs" \
    -comp lz4 -noappend -b 256K -info

# 4. Create the "Portal" ISO (FIXED: Exact flags for BIOS stability)
echo "💿 Rebuilding Boot Info Tables..."
sudo xorriso -as mkisofs \
    -iso-level 3 \
    -full-iso9660-filenames \
    -volid "FurryOS" \
    -eltorito-boot isolinux/isolinux.bin \
    -eltorito-catalog isolinux/boot.cat \
    -no-emul-boot -boot-load-size 4 -boot-info-table \
    ${MBR_BIN:+-isohybrid-mbr "$MBR_BIN"} \
    -output "$TEST_ISO" "$ISO_ROOT" 2>/dev/null

# 5. Launch with "Soul" (High Res + Smooth Mouse)
echo "🚀 Portal Open. Master Tempter is arriving..."
sudo qemu-system-x86_64 \
    -cdrom "$TEST_ISO" \
    -m 2048M \
    -smp cores=4,threads=2 \
    -enable-kvm -cpu host \
    -vga virtio \
    -display gtk,gl=on,zoom-to-fit=on \
    -usb -device usb-tablet

# 6. Cleanup
sudo rm -f "$TEST_ISO"
